package com.netty.messagepack;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class EchoClientHandler extends ChannelHandlerAdapter {
    private final int sendNum;

    public EchoClientHandler(int sendNum){
        this.sendNum = sendNum;
    }
    /**
     * 连接服务端成功后开始发送消息
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        UserInfo [] userInfos = userInfo();
        for (UserInfo userInfo: userInfos) {
            ctx.writeAndFlush(userInfo);
        }
        // ctx.writeAndFlush(userInfos[0]);
    }
    private UserInfo [] userInfo(){
        UserInfo [] userInfos = new UserInfo[sendNum];
        for (int i = 0; i < sendNum; i++){
            UserInfo userInfo = new UserInfo();
            userInfo.setAge(i);
            userInfo.setName("ABCDEF------->" + i);
            userInfos[i] = userInfo;
        }
        return userInfos;
    }
    /**
     * 读取客户端的返回消息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Client receive the msgpack messag:" + msg);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
    /**
     * 发生异常时关闭ctx
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}

